import React, { useEffect } from 'react';
import { List, Checkbox, Modal } from 'antd-mobile';
import styles from './index.less';

const { CheckboxItem } = Checkbox;
const CheckboxPop = React.forwardRef(({ dataSource = [], onClose, visible, value, onChange, ...rest }, ref) => {
    const [selectData, setSelectData] = React.useState([]);
    const handleChange = (v, e) => {
        let selectArr = [...selectData];
        if (e.target.checked === true) {
            selectArr.push(v);
        } else {
            const newData = selectArr.filter(item => item !== v);
            selectArr = newData;
        }
        setSelectData(selectArr);
    };

    // 关闭专业软件弹窗
    const handleCancel = () => {
        onClose(false);
        onChange(value);
        setTimeout(() => {
            setSelectData(value);
        }, 100);
    }
    // 关闭专业软件弹窗
    const handleSure = () => {
        onClose(false);
        onChange(selectData);
    }

    useEffect(() => {
        setSelectData(value)
    }, [value]);
    return (
        <div ref={ref} {...rest}>
            <Modal
                popup
                visible={visible}
                animationType="slide-up"
                maskClosable={false}
                title={
                    <div className={styles.titleCtr}>
                        <span className={styles.cancelBtn} onClick={handleCancel}>取消</span>
                        <span className={styles.titleInfo}>选择软件</span>
                        <span className={styles.sureBtn} onClick={handleSure}>确定</span>
                    </div>}
            >
                <List>
                    {dataSource.map(i =>
                        (
                            <CheckboxItem key={i.id}
                                onChange={e => handleChange(i.softName, e)}
                                checked={selectData?.indexOf(i.softName) > -1}>
                                {i.softName}
                            </CheckboxItem>
                        )

                    )}
                </List>
            </Modal>
        </div>)
});

export default CheckboxPop;
